<?php
namespace addons\csminvite\library;

/**
 * Notify类型
 * test:
 * http://127.0.0.1/fastadmin_plugin_csmmeet/public/index/user/register.html?csminvite=qd_A001_0&csminvitesign=1fd49c07bffb03089c731391d03c6685
 */
class CsminviteQd extends CsminviteNotifyType
{

    /**
     * 获取通知类型邀请函（到user维度Row），并校验链接是否可注册
     */
    public function getAndCheckByInvkey($invkey, $invid)
    {
        if (CsmUtils::isNullOrBlank($invkey)) {
            $this->_error("参数错误：csminvite#2");
        }
        $dao = new \app\admin\model\csminvite\Qd();
        $row = $dao->alias("a1")
            ->where("a1.status", "=", "normal")
            ->where("a1.invitekey", "=", $invkey)
            ->field("a1.*")
            ->find();
        if (! $row) {
            $this->_error("邀请链接错误，请联系网站管理员");
        }
        // 判断是否在有效期内
        $now = time();
        if ($now < $row->effectbegintime) {
            $this->error("邀请链接从" . date('Y-m-s h:i', $row->effectbegintime) . "开始，目前无法注册!");
        }
        if ($now > $row->effectendtime) {
            $this->error("邀请链接在" . date('Y-m-s h:i', $row->effectendtime) . "已经过期，无法注册!");
        }
        $dao = new \app\admin\model\csminvite\Qduser();
        $count = $dao->alias("t")
            ->where("t.status", "=", "normal")
            ->where("t.csminvite_qd_id", "=", $row->id)
            ->where("t.userstatus", "=", "registed")
            ->count();

        // 是否已经用完
        if ($count >= $row->maxuser) {
            $this->error("邀请链接邀请名额已经用完，无法注册!");
        }
        return $row;
    }

    /**
     * Notify类型：记录邀请链接访问时间
     */
    public function visitRegisterUrl($row)
    {
        $param = [
            'lastseetime' => time(),
            'updatetime' => time(),
            'seecount' => $row->seecount + 1
        ];
        // 首次注册
        if ($row->seecount == 0) {
            $param['firstseetime'] = time();
        }
        $dao = new \app\admin\model\csminvite\Qd();
        $dao->where("id","=",$row->id)->update($param);
    }

    /**
     * 注册成功后调用，回写notifyuser
     */
    public function afterRegistered($dbuser, $invkey, $invid)
    {
        $dao = new \app\admin\model\csminvite\Qd();
        $row = $dao->alias("a1")
        ->where("a1.status", "=", "normal")
        ->where("a1.invitekey", "=", $invkey)
        ->field("a1.*")
        ->find();
        if($row==null){
            return;
        }
        
        $dao = new \app\admin\model\csminvite\Qduser();
        $param = [
            "csminvite_qd_id"=>$row->id,
            "userstatus"=>'registed',
            "registedtime"=>time(),
            "registeddate"=>date("Y-m-d"),
            "status"=>"normal",
            "user_id"=>$dbuser->id
        ];
        $dao->create($param);
    }
}